// 公共库
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Box,
  List,
  ListItem,
  ListItemText,
  Divider,
  Breadcrumbs,
  Typography,
} from "@mui/material";

// 本地通用组件和方法
import {
  RowFlexBoxSC,
  ColumnFlexBoxSS,
  ColumnFlexBoxSB,
  highlightKeywords,
  RowFlexBoxEC
} from "../../components/common/Common";
import { formattedDate } from "../../components/common/utilities.js";
import { formattedSearchData } from "../../components/advancedSearchButton/Common.jsx";
import SortMenu from "./SortMenu.jsx";
/**
 * 这是法律条文列表部分的组件
 * @param {object} advancedSearchResult
 * @param {object} searchData
 * @returns
 */
export default function LegislationList({ advancedSearchResult, searchData }) {
  const CHINESE_VALID = { true: "现行有效", false: "现行无效" };
  const [keywords, setKeywords] = useState(searchData.keywords || "");
  const [showNum, setShowNum] = useState(3);
  const formattedData = formattedSearchData("submit", searchData);
  useEffect(() => {
    if (searchData) {
      setKeywords(searchData.keywords || "");
    }
  }, [searchData]);

  // 获取路径的指定节点
  const getNodeTextHistory = (path) => {
    return path[0].revisionHistory[0];
  };

  // 获取搜索到的节点的条信息
  const getArticle = (path) => {
    return path.filter((item) => item.type === "article")[0];
  };

  // 展开更多
  const handleExtend = (lawTitle, maxItemNum) => {
    setShowNum((prevShowNum) => {
      const currentNum = prevShowNum[lawTitle] || 3; // 获取当前法律的展示数量
      if (currentNum + 3 < maxItemNum) {
        return { ...prevShowNum, [lawTitle]: currentNum + 3 }; // 增加数量
      } else {
        return { ...prevShowNum, [lawTitle]: maxItemNum }; // 设置为最大数量
      }
    });
  };

  /**
   * 分页处理
   */
  return (
    <ColumnFlexBoxSB>
      {/**功能区 */}
      {/**TODO逻辑实现 */}
      <RowFlexBoxEC >
      <Typography>排序:</Typography>
      <SortMenu />
      </RowFlexBoxEC>
      {/*分割线 */}
      <Divider sx={{ width: "100%" }} />
      <List sx={{ fontSize: "14px" }}>
        {advancedSearchResult.searchRes && !formattedData.fullText
          ? advancedSearchResult.searchRes.map((item) => (
              // eslint-disable-next-line react/jsx-key
              <Box key={item._id}>
                <ListItem
                  sx={{
                    minHeight: "120px",
                    "&:hover": {
                      backgroundColor: "rgba(0, 0, 0, 0.02)", // 可选：鼠标悬停时的背景颜色
                    },
                  }}
                >
                  <ColumnFlexBoxSS>
                    <RowFlexBoxSC>
                      <Link
                        to={`/legal-instruments/${item._id}`}
                        style={{ textDecoration: "none", color: "inherit" }}
                      >
                        <p style={{ fontSize: "15px" }}>
                          {highlightKeywords(item.title, keywords)}
                        </p>
                      </Link>
                    </RowFlexBoxSC>
                    <RowFlexBoxSC
                      sx={{
                        pl: "22px",
                        mt: 1,
                      }}
                    >
                      <Breadcrumbs aria-label="breadcrumb">
                        <ListItemText primary={CHINESE_VALID[item.isValid]} />
                        <ListItemText primary={item.publishDepartment} />
                        <ListItemText
                          primary={`${formattedDate(item.publishedAt)}  发布`}
                        />
                        <ListItemText
                          primary={`${formattedDate(item.publishedAt)}  实施`}
                        />
                      </Breadcrumbs>
                    </RowFlexBoxSC>
                  </ColumnFlexBoxSS>
                </ListItem>
                <Divider />
              </Box>
            ))
          : advancedSearchResult.searchedRoots.laws &&
            advancedSearchResult.searchedRoots.laws.map((law) => {
              const currentShowNum = showNum[law.title] || 3; // 获取当前法律的展示数量
              return (
                // 确保返回 JSX
                <Box key={law._id}>
                  <ListItem sx={{ px: 0, height: "auto" }}>
                    <ColumnFlexBoxSS>
                      <RowFlexBoxSC>
                        <Link
                          to={`/legal-instruments/${law._id}`}
                          style={{ textDecoration: "none", color: "inherit" }}
                        >
                          <ListItemText primary={law.title} />
                        </Link>
                      </RowFlexBoxSC>
                      <RowFlexBoxSC sx={{ pl: "22px" }}>
                        <Breadcrumbs aria-label="breadcrumb">
                          <ListItemText primary={CHINESE_VALID[law.isValid]} />
                          <ListItemText primary={law.publishDepartment} />
                          <ListItemText
                            primary={`${formattedDate(law.publishedAt)}  发布`}
                          />
                          <ListItemText
                            primary={`${formattedDate(law.publishedAt)}  实施`}
                          />
                        </Breadcrumbs>
                        <br />
                      </RowFlexBoxSC>
                    </ColumnFlexBoxSS>
                  </ListItem>
                  {/* submenu start */}
                  {
                    <Box
                      className="subitem"
                      sx={{
                        backgroundColor: (theme) => theme.palette.subMenu.main,
                        width: "80%",
                        borderRadius: "3px",
                        fontSize: "13px",
                        my: "20px",
                        ml: "20px",
                        border: (theme) => `${theme.palette.subMenu.border} 1px solid`,
                      }}
                    >
                      <Box
                        sx={{
                          fontSize: "13px",
                          color: "#218fc4",
                          height: "40px",
                          lineHeight: "40px",
                          fontWeight: "none",
                          paddingLeft: "15px",
                          borderBottom: (theme) => `${theme.palette.subMenu.border} 1px solid`,
                        }}
                      >
                        共有
                        {advancedSearchResult.searchedRoots[law.title].length}
                        条匹配项
                      </Box>
                      {advancedSearchResult.searchedRoots[law.title]
                        .slice(0, currentShowNum)
                        .map((itemPath) => (
                          <ListItem
                            sx={{
                              height: "auto",
                              width: "100%",
                            }}
                            key={itemPath[0]._id}
                          >
                            <Box>
                              {getNodeTextHistory(itemPath).text ? (
                                <p>
                                  <span
                                    style={{
                                      paddingRight: "1rem",
                                      fontWeight: "bold",
                                    }}
                                  >
                                    {getArticle(itemPath).title}
                                  </span>
                                  {highlightKeywords(
                                    getNodeTextHistory(itemPath).text,
                                    keywords
                                  )}
                                </p>
                              ) : (
                                <p>
                                  {highlightKeywords(
                                    itemPath[0].title,
                                    keywords
                                  )}
                                </p>
                              )}
                            </Box>
                          </ListItem>
                        ))}
                      {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
                      <Box
                        className="extend"
                        onClick={() => handleExtend(
                            law.title,
                            advancedSearchResult.searchedRoots[law.title].length
                          )}
                        sx={{
                          borderTop: (theme) => `${theme.palette.subMenu.border} 1px solid`,
                          display: "block",
                          fontSize: "13px",
                          height: "30px",
                          lineHeight: "30px",
                          paddingLeft: "15px",
                          cursor: "pointer",
                          color: "#aaa",
                          textAlign: "center",
                        }}
                      >
                        展开更多
                      </Box>
                    </Box>
                  }
                  {/* submenu end */}
                  <Divider />
                </Box>
              );
            })}
      </List>
    </ColumnFlexBoxSB>
  );
}
